﻿using System.Windows;
using System.Windows.Controls;
using Pfz.Extensions;

namespace Pfz.WpfControls
{
	/// <summary>
	/// Base control used by those controls that create their own content by some of its properties.
	/// Gives some methods to control the creation/recreation of its content.
	/// </summary>
	public class ContentCreatorControl:
		UserControl
	{
		private bool _mustCreate = true;

		/// <summary>
		/// Creates the Content now, and returns a value indicating if it was created (false if it was
		/// already created).
		/// </summary>
		/// <returns></returns>
		public bool CreateContentNowIfNeeded()
		{
			if (_mustCreate)
			{
				_mustCreate = false;
				OnCreateContent();
				return true;
			}

			return false;
		}
		private void _CreateContentNowIfNeeded()
		{
			CreateContentNowIfNeeded();
		}

		/// <summary>
		/// Tells the control that it must recreate its content.
		/// </summary>
		public bool InvalidateContent()
		{
			if (_mustCreate)
				return false;

			_mustCreate = true;
			Dispatcher.BeginInvokeOnce(_CreateContentNowIfNeeded);
			return true;
		}

		/// <summary>
		/// Recreates the content now, if needed.
		/// </summary>
		protected override Size MeasureOverride(Size constraint)
		{
			CreateContentNowIfNeeded();
			return base.MeasureOverride(constraint);
		}

		/// <summary>
		/// Must be implemented to create the content.
		/// </summary>
		protected virtual void OnCreateContent()
		{
		}
	}
}
